<template>
  <van-row class="publish_wrap">
    <nav-bar @goback="$router.go(-1)" @confirm="confirmSave"/>
    <van-form class="form_wrap" label-width="60">
      <van-field :rules="[{ required: true, message: '请输入文章标题' }]" v-model="form.article_title" label="标题" placeholder="请输入文章标题" />
      <van-field
        :value="brandText"
        readonly
        clickable
        is-link
        label="品牌"
        placeholder="选择品牌"
        @click="chooseBrand"
      />
      <van-field v-model="form.color" label="颜色" placeholder="请输入颜色" />
      <van-field
        :rules="[{ required: true, message: '请输入文章内容' }]"
        v-model="form.article_content"
        rows="4"
        autosize
        label="内容"
        type="textarea"
        maxlength="500"
        placeholder="请输入文章内容"
        show-word-limit
      />
      <van-field name="uploader" label="封面图片">
        <template #input>
          <van-uploader v-model="cover_pic" :max-count="1"/>
        </template>
      </van-field>
      <van-field name="uploader" label="详情图片">
        <template #input>
          <van-uploader v-model="fileList" :max-count="9" multiple/>
        </template>
      </van-field>
    </van-form>
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        :columns="menus"
        show-toolbar
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>
  </van-row>
</template>

<script>
import NavBar from '@/components/NavBar'
import api from '@/api/user'
import carApi from '@/api/car'
export default {
  components: { NavBar },
  data () {
    return {
      form: {
        detail_pic: [],
        cover_pic: ''
      },
      showPicker: false,
      menus: [],
      brandText: '',
      fileList: [],
      copyFile: [],
      detail_pic: [],
      cover_pic: []
    }
  },
  created() {},
  methods: {
    async confirmSave() {
      if (!this.form.article_title) {
        this.$toast.fail('请填写文章标题')
        return
      }
      if (!this.form.brand) {
        this.$toast.fail('请选择品牌')
        return
      }
      if (!this.form.article_content) {
        this.$toast.fail('请输入文章内容')
        return
      }
      this.$toast.loading({
        forbidClick: true,
        mask: false,
        duration: 0,
        message: '加载中...'
      })
      // 上传封面图
      const coverFile = Array.from(this.cover_pic, (item) => (item.file))
      this.form.cover_pic = await this.uploadImg(coverFile[0], 1)
      // 上传详情图
      const copyFile = Array.from(this.fileList, (item) => (item.file))
      const urls = []
      for (let i = 0; i < copyFile.length; i++) {
        if (this.form.detail_pic.length === copyFile.length) {
          break
        }
        const url = await this.uploadImg(copyFile[i])
        urls.push(url)
      }
      this.form.detail_pic = JSON.stringify(urls)
      carApi.createCirCle(this.form)
        .then(res => {
          this.$toast.clear()
          if (parseInt(res.code) === 200) {
            this.$toast.success({
              message: '保存成功',
              duration: 2000,
              onClose: () => {
                this.$router.replace({ name: 'UserInfo' })
              }
            })
          }
        })
    },
    async uploadImg(file) {
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('folder', this.form.brand)
        formData.append('file', file)
        api.uploadFile(formData).then((res) => {
          resolve(res.result.file_name)
        })
      })
    },
    onConfirm(item) {
      this.brandText = item.text
      this.form.brand = item.key
      this.showPicker = false
    },
    chooseBrand() {
      this.getCategoryList(() => {
        this.showPicker = true
      })
    },
    getCategoryList(cb) {
      const params = { page_num: 1, page_size: 100 }
      carApi.categoryList(params).then((res) => {
        if (parseInt(res.code) === 200) {
          res.result = Array.from(res.result, (item) => ({ text: item.category_name, key: item.category_brand }))
          this.menus = [...res.result, ...this.menus]
        }
        cb()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.publish_wrap{
  height: 100vh;
  background-color: rgba(153, 153, 153, 0.05);
  .form_wrap{
    background-color: rgba(153, 153, 153, 0.15);
    margin-top: 5px;
  }
}
</style>
